const { isVerify } = require('./auth')
const path = require("path")
const fs = require("fs")
const easyCopy = (obj) => {
    return JSON.parse(JSON.stringify(obj))
}
const addAncestors = (node, ancestors = []) => {
    if (ancestors.length !== 0) {
        node.ancestors = [...ancestors, node.name];
    }
    node.children.forEach(child => addAncestors(child, [...ancestors, node.name]));
}
const buildTree = (data) => {
    const map = new Map();
    data.forEach(item => {
        map.set(item._id.toString(), { ...item._doc, _id: item._id.toString(), children: [] });
    });
    const tree = [];
    data.forEach(item => {
        if (item.parentId === '0') {
            tree.push(map.get(item._id.toString()));
            tree.sort((a, b) => a.order - b.order);
        } else {
            const parent = map.get(item.parentId);
            if (parent) {
                parent.children.push(map.get(item._id.toString()));
                parent.children.sort((a, b) => a.order - b.order);
            }
        }
    });
    tree.forEach(root => addAncestors(root));
    return tree;
}


const koaBodyConfig = (ctx) => {
    if (ctx.path == '/upload') {
        let { status, message } = isVerify(ctx)
        if (status != 200) {

            return
        }
    }
    return {
        multipart: true,
        urlencoded: true,  // 明确启用urlencoded解析
        json: true,        // 同时支持json
        parsedMethods: ['POST', 'PUT', 'PATCH', 'GET', 'DELETE'], // 允许GET请求解析body
        formidable: {
            maxFileSize: 100 * 1024 * 1024,
            uploadDir: path.join(__dirname, '..', '/public/attach'),
            keepExtensions: true,
            onFileBegin: (name, file) => {
                const dirMap = {
                    'attach': 'attach'
                }
                //检测目录是否存在
                if (!fs.existsSync(path.join(__dirname, '..', 'public/attach'))) {
                    fs.mkdirSync(path.join(__dirname, '..', 'public/attach'), { recursive: true });
                }
                if (!dirMap[name]) {
                    throw new Error('文件上传参数错误')
                }
                file.filepath = path.join(__dirname, '..', `public/${dirMap[name]}`, file.newFilename)
            },
            onError: (err) => {
                console.error('File upload error:', err)
            }
        }
    }
}

module.exports = { easyCopy, buildTree, koaBodyConfig }